#coding=utf-8
import sys
import os
from   os.path import abspath, dirname
sys.path.insert(0,abspath(dirname(__file__)))
import tkinter
from   tkinter import *
import Fun
import json
import threading
import time
import numpy as np

uiName="simulation"
ElementBGArray={}
ElementBGArray_Resize={}
ElementBGArray_IM={}

publish_status=True
global deviceid
global position

#路径点
global distance

#路径点间距离
position=np.zeros([0,2])

def get_current_time():
        ct = time.time()
        local_time = time.localtime(ct)
        data_head = time.strftime("%Y%m%d%H%M%S", local_time)
        data_secs = (ct - int(ct)) * 1000
        time_stamp = "%s%03d" % (data_head, data_secs)
        return time_stamp


body={
            "id":"zauto_01",
            "ts":"20210325142909123",
            "gps_time":"124671288",
            "status":"A",
            "pos_type":"RTK2",
            "lat":25.2123511,
            "lon":132.1315321,
            "ele":15.2,
            "heading":25.3,
            "speed":21.5,
            "accel":2.5,
            "pos_quality":"RTK_FIX",
            "hdop":0.3,
            "sats_num":12,
            "brake":20.5,
            "steer":5.5,
            "gear":"D",
            "odom":100,# 里程计，通过两次差值=本次行进距离
            "door":"L1,L2,B1",
            "light":"LR",
            "epb":"OFF",
            "power":65,
            "vevent":0,
            "driver_id":"小高",
            "device_type":"tcs-d-adp-1.0",
            "target_lat":25.2123511,
            "target_lon":132.1315321
            }



#Form 'Form_1's Event :Load
def Form_1_onLoad(uiName):
 
    pass
#Button 'Button_4' 's Command Event :
def Button_4_onCommand(uiName,widgetName):
    def InputCallBack(text):
        Fun.InsertText(uiName,'Text_1',position=tkinter.END,textValue=text,tag='')
        list=text.split(',')
        num=[[float(list[0]),float(list[1])]]
        global position
        position=np.append(position,num,axis=0)
    Fun.InputDialog(width=400,lines=4,bgColor='#EFEFEF',titleText="路径点选择",promptText="请输入路径点坐标",defaultText="",callBackFunction=InputCallBack)
    pass
    
def move_car(current_index):
    from Project1_cmd import mqtt_client
    global position, speed,distance,deviceid,publish_status
    hz=1/int(Fun.GetText(uiName,'Entry_8'))
    speed=float(Fun.GetText(uiName,'Entry_7'))/3.6

    while publish_status and current_index<len(position)-1:

        Fun.SetElementEnable(uiName,'Button_2',False)
        # 获取当前位置和目标位置
        current_x, current_y = position[current_index]     
        next_x, next_y = position[(current_index + 1)%len(position)]     
        # 计算当前位置到下一个位置的距离
        distance = ((next_x - current_x) ** 2 + (next_y - current_y) ** 2) ** 0.5
        start_time = time.time()
        move_distance=0        
        while publish_status and move_distance< distance:
            move_distance = (time.time() - start_time) *speed
            progress=move_distance/distance
            current_position_x = current_x + (next_x - current_x) * progress
            current_position_y = current_y + (next_y - current_y) * progress      
            if abs(current_position_x-next_x)<0.1:
                current_position_x=next_x
            if abs(current_position_y-next_y)<0.1:
                current_position_y = next_y               
            curtime=get_current_time()
            deviceid=Fun.GetText(uiName,'Entry_1')
            body["id"]=Fun.GetText(uiName,'Entry_1')
            body["ts"]=curtime
            body["lat"]=format(current_position_y,".3f")
            body["lon"]=format(current_position_x,".3f")
            body["speed"]=speed
            body["power"]=Fun.GetText(uiName,"Entry_2")
            body["accel"]=Fun.GetText(uiName,"Entry_3")
            body["steer"]=Fun.GetText(uiName,"Entry_4")
            body["device_type"]=Fun.GetText(uiName,"Entry_5")
            body["odom"]=Fun.GetText(uiName,"Entry_6")
            msg={"ts": curtime,"deviceid": deviceid,"body": body}  
            msg_json=json.dumps(msg,ensure_ascii=False)  
            if current_position_x == next_x and current_position_y == next_y:
                mqtt_client.publish("/devices/%s/report"%deviceid,msg_json)
                print(f"{current_position_x:.3f},{current_position_y:.3f}")
                print("end")
                break
                #防止x或y越界
            elif current_position_x > next_x :
                current_position_x = next_x
                mqtt_client.publish("/devices/%s/report"%deviceid,msg_json)
                print(f"{current_position_x:.3f},{current_position_y:.3f}")
                print("xover")
            elif current_position_y > next_y:
                current_position_y = next_y
                mqtt_client.publish("/devices/%s/report"%deviceid,msg_json)
                print(f"{current_position_x:.3f},{current_position_y:.3f}")
                print("yover")
            else:
                #正常上报
                mqtt_client.publish("/devices/%s/report"%deviceid,msg_json)
                print(f"{current_position_x:.3f},{current_position_y:.3f}")           
            time.sleep(hz)  # 控制上报频率为每秒10次
        # 切换到下一个路径点
        current_index = current_index + 1

    Fun.SetElementEnable(uiName,'Button_2',True)

#Button 'Button_2' 's Command Event :
def Button_2_onCommand(uiName,widgetName):    
    global publish_status
    if not publish_status:
        publish_status=True
        initial_index = 0
        def move():
            move_car(initial_index) 
        run_thread = threading.Thread(target=move, args=[])
        run_thread.setDaemon(True)
        run_thread.start() 
    pass
#Button 'Button_3' 's Command Event :
def Button_3_onCommand(uiName,widgetName):
    global publish_status
    publish_status=False
    

    pass
